package org.wlldTest.translate;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import org.dromara.easyai.config.SentenceConfig;
import org.dromara.easyai.config.TfConfig;
import org.dromara.easyai.entity.SentenceModel;
import org.dromara.easyai.entity.TalkBody;
import org.dromara.easyai.entity.WordBack;
import org.dromara.easyai.entity.WordTwoVectorModel;
import org.dromara.easyai.matrixTools.Matrix;
import org.dromara.easyai.matrixTools.MatrixList;
import org.dromara.easyai.matrixTools.MatrixOperation;
import org.dromara.easyai.naturalLanguage.word.WordEmbedding;
import org.dromara.easyai.transFormer.TransFormerManager;
import org.dromara.easyai.transFormer.TransWordVector;
import org.dromara.easyai.transFormer.model.TransFormerModel;
import org.dromara.easyai.transFormer.nerve.SensoryNerve;
import org.wlldTest.MySql.SentenceCode;
import org.wlldTest.MySql.Sql;
import org.wlldTest.lesson7.Word;
import org.wlldTest.myUnet.WordAndId;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * @author lidapeng
 * @time 2025/3/7 13:15
 */
public class Test2 {
    public static TfConfig config = new TfConfig();//最外层配置文件
    public static int wordVectorDimension = 32;//设置词向量维度
    public static TransFormerManager transFormerManager = new TransFormerManager();

    public static void main(String[] args) throws Exception {
        init();
        //test();
        study();
    }

    public static void init() throws Exception {
        List<String> sentenceList = new ArrayList<>();
        List<SentenceCode> sentenceCodes = Sql.sql.getSql().selectList("selectMyWord");
        for (SentenceCode sens : sentenceCodes) {//塞入测试数据s
            sentenceList.add(sens.getQuestion().replace(" ", ""));
            sentenceList.add(sens.getAnswer().replace(" ", ""));
        }
        config.setMaxLength(25);//最大长度设置为40
        config.setMultiNumber(8);//每层编解码器设置3个多头
        config.setFeatureDimension(wordVectorDimension);//设置词向量维度
        config.setAllDepth(1);//设置tf编解码器深度
        //config.setAuto(false);
        //config.setGMaxTh(10000);
        config.setTimes(100);//循环训练五百次
        config.setStudyRate(0.0025f);//设置tf学习率
        config.setTimePunValue(0.5f);//0.5
        config.setShowLog(true);//对学习中的数据打印
        //TransFormerModel transFormerModel = getModel("/Users/lidapeng/job/sayOrderModel/longTalk.json");
        //transFormerManager.insertModel(transFormerModel, config);
        transFormerManager.init(config, sentenceList);
    }

    public static void test() throws Exception {
        String word = "你们回收小米笔记本吗";//你的平板是什么型号
        SensoryNerve sensoryNerve = transFormerManager.getSensoryNerve();
        TransWordVector transWordVector = transFormerManager.getTransWordVector();
        WordBack wordBack = new WordBack();
        String start = "的，你说下小米笔记本的型号信息";//收的，你说下小米笔记本的型号
        sensoryNerve.postSentence(1, word, start, false, wordBack);
        int id = wordBack.getId();
        String nextWord = transWordVector.getWordByID(id);
        System.out.println(nextWord);
    }


    private static List<SentenceCode> anySort(List<SentenceCode> sentences) {//做乱序
        Random random = new Random();
        List<SentenceCode> sent = new ArrayList<>();
        int time = sentences.size();
        for (int i = 0; i < time; i++) {
            int size = sentences.size();
            int index = random.nextInt(size);
            sent.add(sentences.get(index));
            sentences.remove(index);
        }
        return sent;
    }

    public static void study() throws Exception {
        List<SentenceCode> sentenceCodes = anySort(Sql.sql.getSql().selectList("selectMyWord"));
        SensoryNerve sensoryNerve = transFormerManager.getSensoryNerve();
        for (int i = 0; i < 800; i++) {
            System.out.println("i=======" + i);
            for (int k = 0; k < sentenceCodes.size(); k++) {
                SentenceCode sens = sentenceCodes.get(k);
                long eventID;
                if (k % 2 == 0) {
                    eventID = 1;
                } else {
                    eventID = 2;
                }
                String sentence = sens.getQuestion().replace(" ", "");//原语句
                String code = sens.getAnswer().replace(" ", "");//翻译代码
                System.out.println("==============语句:" + sentence + ",转换:" + code);
                sensoryNerve.postSentence(eventID, sentence, code, true, null);
            }
        }
        TransFormerModel transFormerModel = transFormerManager.getModel();
        writeModel(JSON.toJSONString(transFormerModel), "/Users/lidapeng/job/linshi/w0.json");
    }

    public static void writeModel(String model, String url) throws IOException {//写出模型与 激活参数
        OutputStreamWriter out = new OutputStreamWriter(Files.newOutputStream(Paths.get(url)), StandardCharsets.UTF_8);
        out.write(model);
        out.close();
    }

    private static TransFormerModel getModel(String url) {
        File file = new File(url);
        String a = readPaper(file);
        return JSONObject.parseObject(a, TransFormerModel.class);
    }

    private static String readPaper(File file) {
        InputStream read = null;
        String context = null;
        try {
            read = Files.newInputStream(file.toPath());
            byte[] bt = new byte[read.available()];
            read.read(bt);
            context = new String(bt, StandardCharsets.UTF_8);
            read.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (read != null) {
                try {
                    read.close(); //确保关闭
                } catch (IOException el) {
                }
            }
        }
        return context;
    }
}
